<template>
  <div style="padding: 20px ;">
    <div class="header">
      Hi，AI助手已支持DeepSeek-R1最新版，快来试试吧！
    </div>
    <div class="chat-wrap">
      <!-- 对话历史 -->
      <div ref="chatBox" class="chat-history">
        <div v-for="(item,idx) in talkList" :key="idx" :class="item.role==='user'?'mine':'robot'">
          <span v-html="item.html||item.content"/>
        </div>
      </div>
      <!-- 输入区 -->
      <div class="chat-input">
        <el-input v-model="contentVal" placeholder="请输入问题" @keyup.enter.native="send">
          <i slot="suffix" class="el-icon-position el-input__icon" style="cursor:pointer" @click="send"/>
        </el-input>
      </div>
    </div>
  </div>

</template>

<script>
import {uploadServer} from "@/settings";

export default {
  name: 'AiChat',
  data() {
    return {
      contentVal: '',
      talkList: [
        {role: 'robot', content: '你好，有什么可以帮到你？'}
      ]
    };
  },
  mounted() {
    this.scrollBottom();
  },
  updated() {
    this.scrollBottom();
  },
  methods: {
    /* ---------- 发送 ---------- */
    async send() {
      if (!this.contentVal.trim()) return;
      // 1. 用户消息
      this.talkList.push({role: 'user', content: this.contentVal});
      const q = this.contentVal;
      this.contentVal = '';
      // 2. 模型回复占位
      const aiIdx = this.talkList.length;
      this.talkList.push({role: 'robot', content: ''});
      /* ---------- 流式拉取 ---------- */
      try {
        // 这里用 fetch 举例，如需 axios 可改用 axios.post(url,{prompt:q,stream:true}, {responseType:'stream'})
        const resp = await fetch(uploadServer + '/ai/chat/stream', {
          method: 'POST',
          headers: {'Content-Type': 'application/json'},
          // 提示词   prompt  提示词工程
          body: JSON.stringify({prompt: q, stream: true})
        });
        const reader = resp.body.getReader();
        const decoder = new TextDecoder('utf-8');
        let full = '';
        while (true) {
          const {done, value} = await reader.read();
          if (done) break;
          // 逐块解码
          const chunk = decoder.decode(value, {stream: true});
          // 简单处理 SSE 格式：去掉 data: 前缀
          chunk.split('\n').filter(l => l.startsWith('data: ')).forEach(l => {
            console.log(">>>>>", JSON.stringify(l))
            const txt = l.slice(6);
            if (txt === '[DONE]') return;
            try {
              const obj = JSON.parse(txt);
              const delta = obj.choices[0]?.delta?.content || '';
              full += delta;
              // 打字机效果
              this.$set(this.talkList, aiIdx, {
                role: 'robot',
                content: full,
                html: this.formatContent(full)
              });
            } catch (error) {
              console.log(error)
            }
          });
        }
      } catch (e) {
        this.$set(this.talkList, aiIdx, {
          role: 'robot',
          content: '服务器开小差了，稍后再试~'
        });
      }
    },

    /* ---------- 工具 ---------- */
    scrollBottom() {
      this.$nextTick(() => {
        const box = this.$refs.chatBox;
        box.scrollTop = box.scrollHeight;
      });
    },
    formatContent(str) {
      // 把 \n 换成 <br>，让换行在 v-html 里生效
      return str.replace(/\n/g, '<br>');
    }
  }
};
</script>

<style scoped>
.header {
  background: linear-gradient(90deg, #335bff, #ca37ce);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
  display: inline-block;
  font-size: 20px;
  font-style: normal;
  font-weight: 600;
  line-height: 20px;
}

.chat-wrap {
  width: 100%;
  height: 78vh;
  margin: 15px auto;
  border: 1px solid #dcdfe6;
  border-radius: 10px;
  display: flex;
  flex-direction: column;
}

.chat-history {
  flex: 1;
  padding: 10px;
  overflow-y: auto;
}

.chat-input {
  padding: 10px;
  border-top: 1px solid #dcdfe6;
}

/* 气泡样式 */
.robot, .mine {
  margin: 8px 0;
  display: flex;
}

.robot {
  justify-content: flex-start;
}

.mine {
  justify-content: flex-end;
}

.robot span {
  background: #f2f6fc;
  color: #303133;
  padding: 8px 12px;
  border-radius: 0 12px 12px 12px;
  max-width: 70%;
  word-break: break-all;
}

.mine span {
  background: #409eff;
  color: #fff;
  padding: 8px 12px;
  border-radius: 12px 0 12px 12px;
  max-width: 70%;
  word-break: break-all;
}
</style>

